<template>
  <div class="app-container">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <span>批量导入员工</span>
      </div>
      <!-- card body -->
      <UploadExcel :before-upload="beforeUpload" :on-success="onSuccess" />
    </el-card>
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils'
import { importEmployees } from '@/api/employees'
export default {
  methods: {
    beforeUpload (file) {
      return true
    },
    async onSuccess ({ header, results }) {
      try {
        await importEmployees(this.transformResults(results))
        this.$router.back()
      } catch (error) {
        console.log(error)
      }
    },
    transformResults (results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const newarr = []
      results.forEach(person => {
        const newper = {}
        for (const key in person) {
          newper[userRelations[key]] = person[key]
          if (userRelations[key] === 'timeOfEntry' || userRelations[key] === 'correctionTime') {
            // 格式化excel时间
            newper[userRelations[key]] = formatExcelDate(person[key], '-')
          }
        }
        newarr.push(newper)
      })
      return newarr
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
